import store from '@/store';
import { Dict, DictType } from '@/model/common';

export default class DictUtil {
    private static getDictFlagMap = new Map<DictType, boolean>();

    /**
     * 获取字典数据
     */
    public static async get(type: DictType): Promise<Dict[]> {
        while (this.getDictFlagMap.get(type)) {
            await this.sleep(100);
        }
        this.getDictFlagMap.set(type, true);
        // 先从VUEX中取，取到了直接返回，没取到调用接口取，然后存到VUEX中
        const dict = store.getters.dict(type);
        if (dict && dict.length > 0) {
            this.getDictFlagMap.set(type, false);
            return dict;
        }
        await store.dispatch('dict', [type]);
        this.getDictFlagMap.set(type, false);
        return store.getters.dict(type);
    }

    /**
     * 字典数据转换
     * 后端返回的数据结构：{key: '', value: ''}
     * 前端使用Select组件，需要转换为：{key: '', label: ''}
     */
    public static trans(dict: Dict[]): Dict[] {
        const result: Dict[] = [];
        if (dict) {
            dict.forEach((item) => {
                result.push({ key: item.key, value: item.key, label: item.value });
            });
        }
        return result;
    }

    private static sleep(delay: number) {
        return new Promise((resolve) => {
            setTimeout(resolve, delay);
        });
    }
}
